package com.imooc.course.generator.util;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;

public class ReadGeneratorConfigXml {

    private String generatorConfigPath = "server\\src\\main\\resources\\generator\\generatorConfig.xml";

    public static ReadGeneratorConfigXml init(String generatorConfigPath) {
        ReadGeneratorConfigXml rgcp = new ReadGeneratorConfigXml();
        rgcp.generatorConfigPath = generatorConfigPath;
        return rgcp;
    }

    public String getTableName() throws Exception {
        Element tableElement = this.getTableElement(this.generatorConfigPath);
        return tableElement.attributeValue("tableName");
    }

    public String getTableComment() throws Exception {
        return DbUtil.getTableComment(this.getTableName());
    }

    public String getDomainObjectName() throws Exception {
        Element tableElement = this.getTableElement(this.generatorConfigPath);
        return tableElement.attributeValue("domainObjectName");
    }

    public String getLowerCaseDomain() throws Exception {
        String Domain = getDomainObjectName();
        return Domain.substring(0, 1).toLowerCase() + Domain.substring(1);
    }

    private Element getTableElement(String ConfigPath) throws Exception {
        // 只生成配置文件中的第一个table节点
        File file = new File(ConfigPath);
        SAXReader reader=new SAXReader();
        //读取xml文件到Document中
        Document doc=reader.read(file);
        //获取xml文件的根节点
        Element rootElement = doc.getRootElement();
        //读取context节点
        Element contextElement = rootElement.element("context");
        //返回<table>标签
        return contextElement.elementIterator("table").next();
    }

}
